import optparse
import os
import subprocess
import sys
import tempfile

import throttle
from throttle import submit

from resman import resource_managers, set_default_rm
from options import add_options

def write(scripts_dict, path=None):
    if path is None:
        path = os.getcwd()
    elif os.access(path, os.F_OK | os.W_OK):
        if not os.path.isdir(path):
            raise IOError("Cannot write scripts: path `{0}' exists and is not a directory".format(path))
    else:
        os.mkdir(path)

    tot_count = 0

    nscripts = sum(scripts_dict.values())
    for script_obj, count in scripts_dict.iteritems():
        if tot_count % 100 == 0:
            sys.stdout.write("{0}/{1} scripts written\r".format(tot_count, nscripts))
            sys.stdout.flush()

        with open("{0}.{1}x.sh".format(os.path.join(path, script_obj.name), count), 'w') as fp:
            fp.write(str(script_obj))

        tot_count += 1

    print "{0}/{0} scripts written".format(nscripts)

    return tot_count

        
